package com.nsi.service.Impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.ServerResponse;
import com.nsi.dao.ProjectsMapper;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.Projects;
import com.nsi.service.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: Luo Zhen
 * @date: 2018/9/26 10:30
 * @description:
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectsMapper, Projects> implements IProjectService {

    @Autowired
    private ProjectsMapper projectsMapper;

    @Override
    public void addProject(Projects projects) {
        projects.setLoadTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        try {
            projectsMapper.insert(projects);
        } catch (Exception e) {
            throw new NsiOperationException("addProject error:" + e.getMessage());
        }
    }

    @Override
    public ServerResponse getProjectList(String searchKey, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        EntityWrapper<Projects> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(searchKey)) {
            wrapper.like("SubjectName", searchKey)
                    .or()
                    .like("Areas", searchKey)
                    .or()
                    .like("Areas02", searchKey)
                    .or()
                    .like("Areas03", searchKey);
        }
        wrapper.orderBy("Load_time", false);
        List<Projects> projects = projectsMapper.selectList(wrapper);
        PageInfo pageInfo = new PageInfo(projects);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public void modifyProject(Projects projects) throws NsiOperationException {
        try {
            projectsMapper.updateById(projects);
        } catch (Exception e) {
            throw new NsiOperationException("modifyProject error:" + e.getMessage());
        }
    }

    @Override
    public ServerResponse getProjectByUserMail(String userMail) {
        if (StringUtils.isBlank(userMail)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        List<Projects> list = projectsMapper.findProjectByUserMail(userMail);
        return ServerResponse.createBySuccess("返回成功", list.size(), list);
    }
}
